package com.zengqingfa.shardingjdbc.demo.rest;

import com.zengqingfa.shardingjdbc.demo.entity.Bill;
import com.zengqingfa.shardingjdbc.demo.entity.BillDTO;
import com.zengqingfa.shardingjdbc.demo.entity.BillRespDTO;
import com.zengqingfa.shardingjdbc.demo.service.BillService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.hint.HintManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @fileName: BillController
 * @author: zengqf3
 * @date: 2021-1-28 10:45
 * @description:
 */
@RequestMapping("/bill")
@RestController
@Slf4j
public class BillController {

    @Autowired
    BillService billService;

    @PostMapping("/create")
    public BillDTO create(@RequestBody BillDTO bill) {
        BillDTO billResp = billService.create(bill);
        return billResp;
    }

    @GetMapping("/selectByPrimary")
    public Bill selectByPrimary(@RequestParam("id") String id, @RequestParam("tenantCode") String tenantCode) {
        Bill billResp = billService.selectByPrimary(Long.valueOf(id), tenantCode);
        return billResp;
    }

    @GetMapping("/deleteAll")
    public boolean delete() {
        boolean flag=billService.deleteAll();
        return flag;

    }

    @GetMapping("/queryBillAndDetail")
    public List<BillRespDTO> queryBillAndDetail(@RequestParam("id") String id, @RequestParam("tenantCode") String tenantCode) {
        //强制路由主库
        HintManager.getInstance().setMasterRouteOnly();
        List<BillRespDTO> billResp = billService.queryBillAndDetail(Long.valueOf(id), tenantCode);
        return billResp;
    }

    @GetMapping("/testDebug")
    public List<BillRespDTO> testDebug(@RequestParam("id") String id, @RequestParam("tenantCode") String tenantCode) {
        for (int i = 0; i < 3; i++) {
            log.info("i={}", i);
            final int k = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    log.info(Thread.currentThread().getName() + ":" + "i=" + k);
                }
            }).start();
        }
        this.methodOne(methodTwo(20));
        List<BillRespDTO> billResp = billService.queryBillAndDetail(Long.valueOf(id), tenantCode);
        return billResp;
    }

    private Integer methodOne(Integer methodTwo) {
        for (int j = 0; j < methodTwo; j++) {
            log.info("j={}", j);
        }
        return methodTwo;
    }

    private Integer methodTwo(int i) {
        for (int j = 0; j < 5; j++) {
            log.info("j={}", j);
        }
        return 5;
    }
}
